package br.com.vpsa.previdordevendas.model.service.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import br.com.vpsa.previdordevendas.model.entity.Declinio;
import br.com.vpsa.previdordevendas.model.service.DeclinioService;

@Service
public class DeclinioServiceImpl implements DeclinioService
{

    @PersistenceContext
    private EntityManager em;
	
	@Override
	@Transactional
	public void salvarDeclinio(Declinio declinio) {

		em.persist(declinio);
	}
	
	@Override
	public List<Declinio> listarTodos(String base) 
	{
		String hql = "from Declinio i where i.base = :base";

		TypedQuery<Declinio> query = em.createQuery(hql, Declinio.class);
		query.setParameter("base", base);
		
		return query.getResultList();
	}

	@Override
	public List<Declinio> listar(String base, Long idEntidade) 
	{
		String hql = "from Declinio i where i.base = :base";
				
		if( idEntidade != null ){
			hql += " and i.idEntidade = :idEntidade";
		}
		
		TypedQuery<Declinio> query = em.createQuery(hql, Declinio.class);
		query.setParameter("base", base);
		
		if( idEntidade != null ){
			query.setParameter("idEntidade", idEntidade);
		}
			
		return query.getResultList();
	}

	@Override
	@Transactional
	public void remover(long idDeclinio) 
	{
		String hql = "delete from Declinio i where i.id = :idDeclinio";
		
		Query query = em.createQuery(hql);
		query.setParameter("idDeclinio", idDeclinio);
		
		query.executeUpdate();
	}

}
